package dao

import "github.com/jinzhu/gorm"

type Book struct {
	Id       uint   `json:"id" gorm:"primary_key"`
	Name     string `json:"name" gorm:"name"`
	PhoneNum string `json:"phoneNum" gorm:"phone_num"`
	Address  string `json:"address" gorm:"address"`
}

func (t *Book) TableName() string {
	return "book"
}

func (t *Book) FindByID(db *gorm.DB) (*Book, error) {
	out := &Book{}
	err := db.Find(out).Where(t.Name).Table(t.TableName()).Error
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (t *Book) FindList(db *gorm.DB, pageNum int, pageSize int) ([]Book, int64, error) {
	var list []Book
	var count int64

	offset := (pageNum - 1) * pageSize
	query := db.Table(t.TableName()).Where(" (name like ?) ", "%"+t.Name)
	query = query.Count(&count)
	query = query.Limit(pageSize).Offset(offset).Order("id asc").Find(&list)
	err := query.Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, 0, err
	}
	return list, count, nil

}

func (t *Book) Save(db *gorm.DB) error {
	return db.Save(t).Table(t.TableName()).Error
}

func (t *Book) Delete(db *gorm.DB) error {
	return db.Delete(t).Table(t.TableName()).Error
}
